package com.sunzn.media.library;

import android.app.Activity;
import android.content.Intent;
import android.database.Cursor;
import android.graphics.Rect;
import android.os.Bundle;
import android.os.Handler;
import android.os.Looper;
import android.util.Log;
import android.view.View;

import androidx.annotation.NonNull;
import androidx.appcompat.widget.AppCompatImageView;
import androidx.appcompat.widget.AppCompatTextView;
import androidx.fragment.app.Fragment;
import androidx.fragment.app.FragmentActivity;
import androidx.lifecycle.ViewModelProvider;
import androidx.recyclerview.widget.DefaultItemAnimator;
import androidx.recyclerview.widget.ItemTouchHelper;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
import androidx.viewpager2.adapter.FragmentStateAdapter;
import androidx.viewpager2.widget.ViewPager2;

import com.google.android.material.tabs.TabLayout;
import com.google.android.material.tabs.TabLayoutMediator;
import com.sunzn.media.library.adpt.AlbumAdapter;
import com.sunzn.media.library.adpt.MediaAdapter;
import com.sunzn.media.library.adpt.SelectAdapter;
import com.sunzn.media.library.anim.AnimationHelper;
import com.sunzn.media.library.bean.Album;
import com.sunzn.media.library.bean.Item;
import com.sunzn.media.library.drag.MediaCallback;
import com.sunzn.media.library.drag.OnMediaItemTouchListener;
import com.sunzn.media.library.frgm.MediaFragment;
import com.sunzn.media.library.help.SelectedItemCollection;
import com.sunzn.media.library.load.AlbumCollection;
import com.sunzn.media.library.main.AlbumPreviewActivity;
import com.sunzn.media.library.main.BasePreviewActivity;
import com.sunzn.media.library.port.AlbumViewModel;
import com.sunzn.media.library.port.MediaViewModel;

import java.util.ArrayList;
import java.util.List;

import static com.sunzn.media.library.help.SelectedItemCollection.COLLECTION_MIXED;
import static com.sunzn.media.library.load.AlbumMediaLoader.IMAGE;
import static com.sunzn.media.library.load.AlbumMediaLoader.VIDEO;
import static com.sunzn.media.library.load.AlbumMediaLoader.WHOLE;
import static com.sunzn.media.library.main.BasePreviewActivity.EXTRA_RESULT_ORIGINAL_ENABLE;

public abstract class MediaActivity extends FragmentActivity implements AlbumCollection.AlbumCallbacks, MediaFragment.SelectionProvider, MediaAdapter.CheckStateListener, MediaAdapter.OnMediaClickListener, SelectAdapter.RemoveListener, AlbumAdapter.OnAlbumClickListener {

    public static void start(Activity context) {
        Intent intent = new Intent(context, MediaActivity.class);
        context.startActivity(intent);
        context.overridePendingTransition(R.anim.anim_bottom_in, R.anim.anim_page_static);
    }

    private static final int REQUEST_CODE_PREVIEW = 23;
    private AlbumAdapter albumAdapter;
    private AlbumViewModel albumViewModel;
    private RecyclerView albumView;
    private AppCompatTextView title;
    private AlbumCollection collection;
    private FragmentStateAdapter stateAdapter;
    private ArrayList<Fragment> fragments;
    private TabLayout taber;
    private ViewPager2 pager;
    private AppCompatTextView next;
    private AppCompatTextView make;
    private AppCompatImageView close;
    private AppCompatImageView arrow;

    private final SelectedItemCollection mSelectedCollection = new SelectedItemCollection(this);
    private MediaViewModel actionViewModel;
    private RecyclerView holder;
    private SelectAdapter selectAdapter;
    private DefaultItemAnimator animator;

    public abstract void onMake(SelectedItemCollection collection);

    public abstract void onNext(SelectedItemCollection collection);

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_media);
        mSelectedCollection.onCreate(savedInstanceState);
        init();
    }

    private void init() {
        initData();
        initView();
        initPics();
        initPort();
    }

    private void initData() {
        fragments = new ArrayList<>();
        stateAdapter = new FragmentStateAdapter(this) {
            @NonNull
            @Override
            public Fragment createFragment(int position) {
                return fragments.get(position);
            }

            @Override
            public int getItemCount() {
                return 3;
            }

            @Override
            public long getItemId(int position) {
                return super.getItemId(position);
            }

            @Override
            public boolean containsItem(long itemId) {
                return super.containsItem(itemId);
            }
        };
        selectAdapter = new SelectAdapter();
        selectAdapter.RemoveListener(this);

        animator = new DefaultItemAnimator();
        animator.setAddDuration(300);
        animator.setRemoveDuration(300);

        albumAdapter = new AlbumAdapter(this);
    }

    private void initView() {
        close = findViewById(R.id.close);
        title = findViewById(R.id.title);
        arrow = findViewById(R.id.arrow);
        taber = findViewById(R.id.taber);
        pager = findViewById(R.id.pager);
        pager.setOffscreenPageLimit(3);
        pager.getChildAt(0).setOverScrollMode(View.OVER_SCROLL_NEVER);
        next = findViewById(R.id.media_next);
        make = findViewById(R.id.media_make);
        holder = findViewById(R.id.holder);
        holder.setLayoutManager(new LinearLayoutManager(this, LinearLayoutManager.HORIZONTAL, false));
        holder.setItemAnimator(animator);
        holder.setAdapter(selectAdapter);
        holder.addItemDecoration(new RecyclerView.ItemDecoration() {
            @Override
            public void getItemOffsets(@NonNull Rect outRect, @NonNull View view, @NonNull RecyclerView parent, @NonNull RecyclerView.State state) {
                int position = parent.getChildAdapterPosition(view);
                outRect.left = position == 0 ? 30 : 0;
                outRect.right = 30;
                outRect.top = 30;
                outRect.bottom = 30;
            }
        });
        ItemTouchHelper helper = new ItemTouchHelper(new MediaCallback(selectAdapter));
        helper.attachToRecyclerView(holder);
        holder.addOnItemTouchListener(new OnMediaItemTouchListener(holder, new OnMediaItemTouchListener.OnItemListener() {
            @Override
            public void onItemClick(int position) {

            }

            @Override
            public void onItemLongClick(RecyclerView.ViewHolder holder) {
                if (holder instanceof SelectAdapter.ViewHolder) {
                    helper.startDrag(holder);
                }
            }
        }));
        albumView = findViewById(R.id.album);
        albumView.setLayoutManager(new LinearLayoutManager(this));
        albumView.setAdapter(albumAdapter);
    }

    private void initPics() {
        collection = new AlbumCollection();
        collection.onCreate(this, this);
        collection.loadAlbums();
    }

    private void initPort() {
        actionViewModel = new ViewModelProvider(this).get(MediaViewModel.class);
        albumViewModel = new ViewModelProvider(this).get(AlbumViewModel.class);
    }

    @Override
    public void onAlbumLoad(Cursor cursor) {
        albumAdapter.swapCursor(cursor);

        Handler handler = new Handler(Looper.getMainLooper());
        handler.post(new Runnable() {
            @Override
            public void run() {
                cursor.moveToPosition(collection.getCurrentSelection());
                Album album = Album.valueOf(cursor);
                onAlbumSelected(album);
            }
        });
    }

    @Override
    public void onAlbumReset() {
        albumAdapter.swapCursor(null);
    }

    private void onAlbumSelected(Album album) {

        Log.e("TTT", album.toString());
        Log.e("TTT", "fragments.size() = " + fragments.size());

        fragments.clear();
        fragments.add(MediaFragment.instance(album, WHOLE));
        fragments.add(MediaFragment.instance(album, VIDEO));
        fragments.add(MediaFragment.instance(album, IMAGE));
        pager.setAdapter(stateAdapter);
        new TabLayoutMediator(taber, pager, new TabLayoutMediator.TabConfigurationStrategy() {
            @Override
            public void onConfigureTab(@NonNull TabLayout.Tab tab, int position) {
                if (position == 0) {
                    tab.setText("全部");
                }
                if (position == 1) {
                    tab.setText("视频");
                }
                if (position == 2) {
                    tab.setText("照片");
                }
            }
        }).attach();
    }

    @Override
    public SelectedItemCollection provideSelectedItemCollection() {
        return mSelectedCollection;
    }

    @Override
    public void onUpdate() {
        actionViewModel.getAction().setValue(System.currentTimeMillis());
        int count = mSelectedCollection.count();
        next.setText(count == 0 ? "下一步" : "下一步(" + count + ")");
        next.setSelected(count > 0);
        next.setClickable(count > 0);
        make.setClickable(count > 0);
        make.setVisibility(count == 0 ? View.GONE : View.VISIBLE);
        holder.setVisibility(count == 0 ? View.GONE : View.VISIBLE);
        List<Item> items = mSelectedCollection.asList();
        selectAdapter.setData(items);
        holder.smoothScrollToPosition(selectAdapter.getItemCount());
    }

    @Override
    public void onRemove(Item item) {
        mSelectedCollection.remove(item);
        onUpdate();
    }

    @Override
    public void onSwap(List<Item> data) {
        mSelectedCollection.overwrite(data, COLLECTION_MIXED);
        actionViewModel.getAction().setValue(System.currentTimeMillis());
    }

    @Override
    public void onMediaClick(Album album, Item item, int adapterPosition) {
        Intent intent = new Intent(this, AlbumPreviewActivity.class);
        intent.putExtra(AlbumPreviewActivity.EXTRA_ALBUM, album);
        intent.putExtra(AlbumPreviewActivity.EXTRA_ITEM, item);
        intent.putExtra(BasePreviewActivity.EXTRA_DEFAULT_BUNDLE, mSelectedCollection.getDataWithBundle());
        intent.putExtra(EXTRA_RESULT_ORIGINAL_ENABLE, false);
        startActivityForResult(intent, REQUEST_CODE_PREVIEW);
    }

    @Override
    public void onAlbumClick(Album album) {
        title.setText(album.getDisplayName());
        AnimationHelper.startQuitAnim(this, albumView, close, arrow);
        albumViewModel.getAlbum().setValue(album);
    }

    public void onClose(View view) {
        finish();
    }

    public void onAction(View view) {
        int ID = view.getId();
        if (ID == R.id.media_make) {
            onMake(mSelectedCollection);
            return;
        }
        if (ID == R.id.media_next) {
            onNext(mSelectedCollection);
        }
    }

    public void onAlbum(View view) {
        if (albumView.getVisibility() == View.GONE) {
            albumView.setAdapter(albumAdapter);
            AnimationHelper.startIntoAnim(view.getContext(), albumView, close, arrow);
        } else {
            AnimationHelper.startQuitAnim(view.getContext(), albumView, close, arrow);
        }
    }

    @Override
    public void finish() {
        super.finish();
        overridePendingTransition(R.anim.anim_page_static, R.anim.anim_bottom_out);
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (resultCode != RESULT_OK)
            return;

        if (requestCode == REQUEST_CODE_PREVIEW) {
            Bundle resultBundle = data.getBundleExtra(BasePreviewActivity.EXTRA_RESULT_BUNDLE);
            ArrayList<Item> selected = resultBundle.getParcelableArrayList(SelectedItemCollection.STATE_SELECTION);
            int collectionType = resultBundle.getInt(SelectedItemCollection.STATE_COLLECTION_TYPE, SelectedItemCollection.COLLECTION_UNDEFINED);
            mSelectedCollection.overwrite(selected, collectionType);
            actionViewModel.getAction().setValue(System.currentTimeMillis());
        }
    }

}